from rest_framework.authentication import TokenAuthentication
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions
from django.utils import timezone
from datetime import timedelta
from django.conf import settings


class ExpiringTokenAuthentication(TokenAuthentication):
    """
    Token 过期
    """

    def authenticate(self, request):
        key = request.query_params.get('token', '')
        model = self.get_model()
        try:
            token = model.objects.select_related('user').get(key=key)
        except model.DoesNotExist:
            raise exceptions.AuthenticationFailed(_('未知Token~~'))
        if not token.user.is_active:
            raise exceptions.AuthenticationFailed(_('该用户是黑名单~~'))
        # 这里做了一个Token过期的验证
        if timezone.now() > (token.created + timedelta(
                days=settings.TOKEN_EXPIRE)):
            raise exceptions.AuthenticationFailed(_('Token过期, 请重新登录~~'))
        return token.user, token
